package com.woyao;

import android.app.Application;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.squareup.picasso.Picasso;
import com.woyao.core.AreaPopUp;
import com.woyao.core.FileUtil;
import com.woyao.core.model.Area;
import com.woyao.core.model.KeyValueList;
import com.woyao.core.model.ProfileResponse;
import com.woyao.core.model.User;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;
import com.woyao.core.util.StringUtil;

import java.io.FileNotFoundException;
import java.io.IOException;

import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;

import static com.woyao.WoyaoooApplication.userId;

public class AccountActivity extends AppCompatActivity {
    private User user;

    private TextView name;
    private TextView addr;
    private TextView org;

    private TextView role;
    private TextView business;


    private CircleImageView avatar;

    private int current_provinceId = 0;
    private int current_cityId;
    private int current_countyId;
    AreaPopUp popUp = null;

    ProgressDialog progressDialog;
    private String from = "";

    private Integer NAME_CODE = 50;
    private Integer AVART_CODE = 100;
    private Integer ORG_CODE = 300;
    private Integer ROLE_CODE = 400;
    private Integer BUSINESS_CODE = 500;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout

        name = (TextView)findViewById(R.id.id_username);

        name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("type","displayname");
                intent.putExtra( "content", user.getDisplayname() );
                intent.setClass(AccountActivity.this,  InputActivity.class);
                startActivityForResult(intent,NAME_CODE);
            }
        });

        addr = (TextView)findViewById(R.id.id_addr);
        addr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popUp.showPopupWindow();
            }
        });

        avatar = (CircleImageView)findViewById(R.id.id_avatar);
        avatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    // Open default camera
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setType("image/");

                    // start the image capture Intent
                    startActivityForResult(intent, AVART_CODE);

                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        });

        org = (TextView)findViewById(R.id.id_organization);

        org.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("type","orgtitle");
                intent.putExtra( "content", user.getOrg() );
                intent.setClass(AccountActivity.this,  InputActivity.class);
                startActivityForResult(intent,ORG_CODE);
            }
        });


        business = (TextView)findViewById(R.id.id_business);

        business.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("from","org");
                KeyValueList kvl = new KeyValueList();
                kvl.setContent(user.getBusiness());
                intent.putExtra("business", kvl);
                intent.setClass(AccountActivity.this, FilterBusiness.class);
                startActivityForResult(intent,BUSINESS_CODE);
            }
        });

        final Button nextbtn = (Button) findViewById(R.id.add_next);

        nextbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if( user.getDisplayname().equals("")) {
                    Common.showSnack( AccountActivity.this, nextbtn, "请填写真实姓名！" ) ;
                    return;
                }

                if( current_provinceId == 0) {
                    Common.showSnack( AccountActivity.this, nextbtn, "请选择地址！" ) ;
                    return;
                }

                if (from != null && from.equals("register")) {
                    Intent intent = new Intent();
                    intent.putExtra("from", from );
                    intent.setClass(AccountActivity.this,FilterHow.class);
                    startActivity( intent);
                }else{
                    finish();
                }

            }
        });




        Intent intent = getIntent();
        from = intent.getStringExtra("from");


        if (from != null && from.equals("register")) {
            this.setTitle("1/4. 填写个人资料");
            nextbtn.setText("下一步");
        }else {
            this.setTitle("我的资料");
            nextbtn.setVisibility(View.INVISIBLE);
        }


        popUp = new AreaPopUp(AccountActivity.this);
        popUp.setInit_province(current_provinceId);
        popUp.setInit_city(current_cityId);
        popUp.setInit_district(current_countyId);

        popUp.setOnSuccessListener(new AreaPopUp.OnSuccessListener() {
            @Override
            public void onSuccess(Area province, Area city, Area district) {
                if(province != null){
                    current_provinceId = province.getId();
                    Common.setProfileAttr("province",current_provinceId+"" );
                }
                if(city!=null){
                    current_cityId = city.getId();
                    Common.setProfileAttr("city",current_cityId +""  );
                }
                if(district != null){
                    current_countyId = district.getId();
                    Common.setProfileAttr("county",current_countyId +""  );
                }
                String area = "";
                if(province != null){
                    area = province.getName();
                }
                if(city != null){
                    area += "/"+city.getName();
                }
                if(district != null){
                    area +="/"+district.getName();
                }
                AccountActivity.this.addr.setText(area);
            }
        });
        popUp.init();

        loadData();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        finish();
        return true;
    }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == NAME_CODE && resultCode ==666 ) {    // 姓名
            CharSequence con = data.getCharSequenceExtra("content");
            if (con == null) return;
            name.setText(con);
            name.setTextColor( ContextCompat.getColor(this, R.color.colorTextPrimary) );
            user.setDisplayname( con.toString());

            Application application = getApplication();
            SharedPreferences shared = application.getSharedPreferences("login", MODE_PRIVATE);
            SharedPreferences.Editor editor = shared.edit();
            editor.putString("displayname", user.getDisplayname());
            editor.commit();
            WoyaoooApplication.displayname = user.getDisplayname();

            Common.setProfileAttr("displayname", con.toString());
        }else if (requestCode == AVART_CODE && resultCode == RESULT_OK) {

            try{
                Uri selectedImage = data.getData();

                Bitmap preview =null;
                try {
                    preview =  FileUtil.decodeUri(selectedImage, AccountActivity.this);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                selectedImage = data.getData();
                String picturePath  = "";
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(
                        selectedImage, filePathColumn, null, null, null);
                if(cursor!=null) {
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    picturePath = cursor.getString(columnIndex);
                    cursor.close();
                }
                else
                {
                    picturePath = selectedImage.getPath();
                }

                avatar.setImageBitmap(preview);
                uploadAvatar(picturePath);
            }catch(Exception e){
                e.printStackTrace();
            }
        }else if(requestCode == BUSINESS_CODE && resultCode == 666){
            KeyValueList result = (KeyValueList) data.getExtras().get("result");
            user.setBusiness(result.getContent());
            business.setText(Common.KeyValueToNames( result.getContent()));
            Common.setProfileAttr( "business" , Common.KeyValueToNos( result.getContent()));
        }else if(requestCode == ORG_CODE  ) {
            CharSequence con = data.getCharSequenceExtra("content");
            if (con == null) return;
            org.setText(con);
            org.setTextColor( ContextCompat.getColor(this, R.color.colorTextPrimary) );
            user.setOrg( con.toString());
            Common.setProfileAttr("org", con.toString());
        }else if(requestCode == ROLE_CODE  ) {
            CharSequence con = data.getCharSequenceExtra("content");
            if (con == null) return;
            role.setText(con);
            role.setTextColor( ContextCompat.getColor(this, R.color.colorTextPrimary) );
            user.setRole( con.toString());
            Common.setProfileAttr("role", con.toString());
        }
    }

    private void uploadAvatar(  String localpicpath){
        final String filename =  FileUtil.getAvatarObjectKey();
        OSS oss = FileUtil.getOss(getApplicationContext());
        PutObjectRequest put = new PutObjectRequest(FileUtil.bucketName, filename, localpicpath);

// 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {

            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Common.setProfileAttr("snailview", "aliyun"+ filename);
                Common.showSnack(AccountActivity.this,avatar,"上传成功");
//                Toast.makeText(AccountActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常

                }
                Common.showSnack(AccountActivity.this,avatar,"上传失败");
            }
        });

    }

    private void loadData(){
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在获取数据······");
        progressDialog.show();

        AsyncTask<Void,Void,ProfileResponse> loadTask =
                new AsyncTask<Void, Void, ProfileResponse>() {
                    @Override
                    protected ProfileResponse doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);
                        Call<ProfileResponse> responseCall = svc.getProfile(userId,"android");
                        try {
                            ProfileResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }
                    @Override
                    protected void onPostExecute(final ProfileResponse response) {
                        if(response != null && response.isSuccess()){
                            renderAccount(response);
                        }
                        progressDialog.dismiss();
                    }
                };
        loadTask.execute((Void)null);
    }



    private void renderAccount(ProfileResponse response){
        this.user = response.getContent();

        Application application = getApplication();
        SharedPreferences shared = application.getSharedPreferences("login", MODE_PRIVATE);

        SharedPreferences.Editor editor = shared.edit();
        editor.putString("displayname", user.getDisplayname());
        editor.commit();
        WoyaoooApplication.displayname = user.getDisplayname();

        name.setText(user.getDisplayname());

        if ( user.getDisplayname().equals("") ) {
            name.setText("请填写真实姓名");
        }else {
            name.setText(user.getDisplayname());
        }

        business.setText( Common.KeyValueToNames( user.getBusiness() )   );

        addr.setText(  user.getLocation());

        if ( user.getProvince()== 0 ) {
            addr.setText("请选择地址");
        }else {
            addr.setText(user.getLocation());
        }

        current_countyId = user.getCounty();
        current_provinceId = user.getProvince();
        current_cityId = user.getCity();

        String snail = user.getSnailview();
        if (StringUtil.notNullOrEmpty(snail)) {

            Picasso.with(this)
                    .load(snail)
                    .into(avatar);
        }
//        //render avatar
//        GetObjectRequest get = new GetObjectRequest(FileUtil.bucketName, FileUtil.getAvatarObjectKey());
//
//        OSSAsyncTask task = FileUtil.getOss(AccountActivity.this)
//                .asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
//            @Override
//            public void onSuccess(GetObjectRequest request, GetObjectResult result) {
//                // 请求成功
//                InputStream inputStream = result.getObjectContent();
//                Bitmap avatar = BitmapFactory.decodeStream(inputStream);
//                AccountActivity.this.avatar.setImageBitmap(avatar);
//            }
//
//            @Override
//            public void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
//                // 请求异常
//                if (clientExcepion != null) {
//                    // 本地异常如网络异常等
//                    clientExcepion.printStackTrace();
//                }
//                if (serviceException != null) {
//                    // 服务异常
//                }
//            }
//        });
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            setResult(0, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
